package com.qk.management.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.activity.ActivityDTO;
import com.qk.entity.Activity;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 *
 * @author blusr
 * @version 1.0
 * @date 2025/10/9 10:07
 */
@Service
@SuppressWarnings("all")
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;

    @Override
    public List<Activity> getByChannel(Integer channel) {
        return activityMapper.selectByChannel(channel);
    }

    @Override
    public void update(Activity activity) {
        judgeIsNull(activity);
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.updateById(activity);
    }

    @Override
    public Activity getById(Integer id) {
        return activityMapper.selectById(id);
    }

    @Override
    public void delete(Integer id) {
        activityMapper.delete(id);
    }

    @Override
    public void add(Activity activity) {
        judgeIsNull(activity);
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.insert(activity);
    }

    @Override
    public PageResult<Activity> page(ActivityDTO activityDTO) {
        PageHelper.startPage(activityDTO.getPage(), activityDTO.getPageSize());
        List<Activity> list = activityMapper.list(activityDTO);
        Page<Activity> page = (Page<Activity>) list;
        return PageResult.<Activity>builder()
                .rows(page.getResult())
                .total(page.getTotal())
                .build();
    }

    private void judgeIsNull(Activity activity) {
        boolean hasNull = false;
        if (activity.getType() == 1) {
            hasNull = BeanUtil.hasNullField(activity,"id","voucher","createTime","updateTime");
        } else if (activity.getType() == 2) {
            hasNull = BeanUtil.hasNullField(activity,"id","discount","createTime","updateTime");
        }
        if (hasNull) {
            throw new RuntimeException("参数不能为空");
        }
    }
}
